package com.loie.datacenter.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Base64;


public
class FiledownUtil {

    public static
    void main(String[] args) throws Exception {


        String fileURL = "https://qc-dximg3.oss-cn-hangzhou.aliyuncs.com/qc/25/2/11/1336459_67aabb068e858b521593e971_18aa63a34f01.png";
        String savePath = "D:\\packageDocumen.png";

        downloadFile(fileURL, savePath);

    }

    public static
    void downloadFile(String fileURL, String savePath) throws Exception {

        URL url = new URL(fileURL);
        InputStream is = url.openStream();

        FileOutputStream fos = new FileOutputStream(savePath);

        byte[] buffer = new byte[2048];
        int length;

        while ((length = is.read(buffer)) != -1) {
            fos.write(buffer, 0, length);
        }

        fos.close();
        is.close();

        System.out.println("File downloaded successfully!");
    }

    public static
    byte[] toByteArray(String fileURL) throws IOException {
        URL url = new URL(fileURL);
        InputStream is = url.openStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        byte[] buffer = new byte[2048];
        int len;

        // 从输入流中读取字节并将它们存储在缓冲区中
        while ((len = is.read(buffer)) != -1) {
            // 将缓冲区中的字节写入输出流
            os.write(buffer, 0, len);
        }

        return os.toByteArray();
    }
    public static byte[] convertWithBuffer(String filePath) throws IOException {
        File file = new File(filePath);
//        validateImageFile(file); // 文件验证

        try (FileInputStream fis = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[8192]; // 8KB缓冲区
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
//                checkMemorySafety(bos); // 内存安全检测
            }
            return bos.toByteArray();
        }
    }
    public static byte[] convertPngBytesToJpgBytes(byte[] pngBytes, float quality) throws IOException {
        // 读取PNG字节数组
        BufferedImage pngImage;
        try (ByteArrayInputStream bais = new ByteArrayInputStream(pngBytes)) {
            pngImage = ImageIO.read(bais);
            if (pngImage == null) throw new IOException("无效的PNG数据");
        }

        // 创建RGB格式画布（解决JPG不支持透明通道问题）
        BufferedImage jpgImage = new BufferedImage(
                pngImage.getWidth(),
                pngImage.getHeight(),
                BufferedImage.TYPE_INT_RGB
        );

        // 绘制并填充透明区域为白色背景
        Graphics2D graphics = jpgImage.createGraphics();
        graphics.setComposite(AlphaComposite.Src);
        graphics.drawImage(pngImage,  0, 0, Color.WHITE, null);
        graphics.dispose();

        // 配置JPEG压缩参数
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
            try (ImageOutputStream ios = ImageIO.createImageOutputStream(baos))  {
                writer.setOutput(ios);
                ImageWriteParam param = writer.getDefaultWriteParam();
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                param.setCompressionQuality(quality);  // 推荐0.9-0.95
                writer.write(null,  new IIOImage(jpgImage, null, null), param);
            }
            return baos.toByteArray();
        }
    }
    public static void convertPngToJpg(File pngFile, File jpgFile, float quality) throws IOException {
        // 读取原始PNG图像
        BufferedImage pngImage = ImageIO.read(pngFile);

        // 创建无透明通道的RGB图像（解决JPG不支持Alpha问题）
        BufferedImage jpgImage = new BufferedImage(
                pngImage.getWidth(),
                pngImage.getHeight(),
                BufferedImage.TYPE_INT_RGB
        );

        // 绘制并丢弃Alpha通道
        jpgImage.createGraphics().drawImage(pngImage,  0, 0, Color.WHITE, null);

        // 配置JPEG压缩参数
        try (ImageOutputStream output = ImageIO.createImageOutputStream(jpgFile))  {
            ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
            writer.setOutput(output);

            ImageWriteParam param = writer.getDefaultWriteParam();
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(quality);  // 0.0~1.0质量参数

            writer.write(null,  new IIOImage(jpgImage, null, null), param);
            writer.dispose();
        }
    }

        /**
         * 将 PNG 字节数组转换为 JPG 字节数组
         * @param pngBytes PNG 图像的字节数组
         * @param quality  JPG 质量（0.0-1.0）
         * @return JPG 图像的字节数组
         * @throws IOException 图像处理异常
         */
        public static byte[] convertPngToJpg(byte[] pngBytes, float quality) throws IOException {
            // 将 PNG 字节数组转换为 BufferedImage
            ByteArrayInputStream pngInputStream = new ByteArrayInputStream(pngBytes);
            BufferedImage bufferedImage = ImageIO.read(pngInputStream);
            fillTransparentBackground(bufferedImage, Color.WHITE);

            // 将 BufferedImage 转换为 JPG 字节数组
            ByteArrayOutputStream jpgOutputStream = new ByteArrayOutputStream();

            // 设置 JPG 压缩质量
            javax.imageio.plugins.jpeg.JPEGImageWriteParam jpegParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
            jpegParams.setCompressionMode(javax.imageio.plugins.jpeg.JPEGImageWriteParam.MODE_EXPLICIT);
            jpegParams.setCompressionQuality(quality);

            // 获取 JPG 写入器
            javax.imageio.ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
            writer.setOutput(ImageIO.createImageOutputStream(jpgOutputStream));
            writer.write(null, new javax.imageio.IIOImage(bufferedImage, null, null), jpegParams);
            writer.dispose();

            // 返回 JPG 字节数组
            return jpgOutputStream.toByteArray();
        }
    public static void fillTransparentBackground(BufferedImage image, Color fillColor) {
        Graphics2D g2d = image.createGraphics();
        g2d.setColor(fillColor);
        g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
    }


    public static byte[] base64String2ByteFun(String base64Str){
        return Base64.getDecoder().decode(base64Str);
    }

    public static
    void convertByteArrayToFile(String filename, byte[] datas) throws Exception {

        if (datas != null) {
//            String filepath ="E:\\" + filename;
            File file = new File(filename);
            if (file.exists()) {
                file.delete();
            }


            BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(datas));
            FileOutputStream fileOutputStream = new FileOutputStream(filename);
            BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);

            int data;
            while ((data = bis.read()) != -1) {
                bos.write(data);
            }
            bos.flush();
            bos.close();

        }

    }
    public static  JsonNode searchJson(JsonNode node, String key) {
        String value="";
        if (node.has(key)) {
            //System.out.println("Found value: " + node.get(key));
            //value= node.toString();
            //System.out.println("value"+value);
            System.out.println(node);
            return node.get(key);

        }

        if (node.isObject()) {
            for (JsonNode child : node) {
                searchJson(child, key);
            }
        }

        if (node.isArray()) {
            for (JsonNode child : node) {
                searchJson(child, key);
            }
        }

        return null;


    }

    public static Object findKey(JSONObject json, String key) {
        if (json.containsKey(key)) {
            return json.get(key);
        }

        for (String k : json.keySet()) {
            Object value = json.get(k);

            if (value instanceof JSONObject) {
                Object result = findKey((JSONObject)value, key);
                if (result != null) {
                    return result;
                }
            } else if (value instanceof JSONArray) {
                JSONArray array = (JSONArray)value;
                for (int i = 0; i < array.size(); i++) {
                    Object element = array.get(i);
                    if (element instanceof JSONObject) {
                        Object result = findKey((JSONObject)element, key);
                        if (result != null) {
                            return result;
                        }
                    }
                }
            }
        }
        return null;
    }



}

